package com.briup.estore.web.servlet;

import com.briup.estore.common.constant.ExceptionMsgEnum;
import com.briup.estore.common.exception.EstoreException;
import com.briup.estore.common.result.Result;
import com.briup.estore.common.utils.JsonUtils;
import com.briup.estore.common.utils.LogUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Author briup-adam
 * @Date 2023/8/3 上午9:34
 * @Description  servlet统一父类   提供请求体数据读取  以及响应体填充数据输出方法
 **/

public  class BaseServlet  extends HttpServlet {

    protected Logger log= LogUtils.log();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      throw  new EstoreException(ExceptionMsgEnum.METHOD_NOT_ALLOW);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        throw  new EstoreException(ExceptionMsgEnum.METHOD_NOT_ALLOW);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        throw  new EstoreException(ExceptionMsgEnum.METHOD_NOT_ALLOW);

    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        throw  new EstoreException(ExceptionMsgEnum.METHOD_NOT_ALLOW);

    }

    public void  writeData(HttpServletResponse response, Result data) throws IOException {
        response.setStatus(200);
        String json = JsonUtils.toJson(data);

        ServletOutputStream os = response.getOutputStream();
        os.write(json.getBytes());
        os.flush();
        os.close();
        log.debug("response body:"+json);
    }
    public String readData(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder sb=new StringBuilder("");
        String line=null;
        while ((line=reader.readLine())!=null){
            sb.append(line);
        }
        reader.close();
        log.debug("request body:"+sb.toString());
        return  sb.toString();

    }

}
